package me.wangqu.weiyouqu.web.rest;

import com.codahale.metrics.annotation.Timed;
import me.wangqu.weiyouqu.domain.ShareInfo;
import me.wangqu.weiyouqu.repository.ShareInfoRepository;
import me.wangqu.weiyouqu.security.AuthoritiesConstants;
import me.wangqu.weiyouqu.web.rest.util.HeaderUtil;
import me.wangqu.weiyouqu.web.rest.util.PaginationUtil;
import me.wangqu.weiyouqu.web.rest.dto.ShareInfoDTO;
import me.wangqu.weiyouqu.web.rest.mapper.ShareInfoMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.annotation.Secured;
import org.springframework.web.bind.annotation.*;

import javax.inject.Inject;
import javax.validation.Valid;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * REST controller for managing ShareInfo.
 */
@RestController
@RequestMapping("/api")
public class ShareInfoResource {

    private final Logger log = LoggerFactory.getLogger(ShareInfoResource.class);

    @Inject
    private ShareInfoRepository shareInfoRepository;

    @Inject
    private ShareInfoMapper shareInfoMapper;

    /**
     * 获取分享链接信息
     * @param type
     * @return
     */
    @RequestMapping(value = "/share-infos/type/{type}",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE)
    @Timed
    public ResponseEntity<ShareInfo> getShareInfoByType(@PathVariable Integer type) {
        log.debug("REST request to get ShareInfo : {}", type);
        return shareInfoRepository.findOneByType(type).map(shareInfo -> {
            return new ResponseEntity<>(shareInfo, HttpStatus.OK);
        }).orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }

    /**
     * POST  /share-infos : Create a new shareInfo.
     *
     * @param shareInfoDTO the shareInfoDTO to create
     * @return the ResponseEntity with status 201 (Created) and with body the new shareInfoDTO, or with status 400 (Bad Request) if the shareInfo has already an ID
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @RequestMapping(value = "/share-infos",
        method = RequestMethod.POST,
        produces = MediaType.APPLICATION_JSON_VALUE)
    @Timed
    @Secured(AuthoritiesConstants.ADMIN)
    public ResponseEntity<ShareInfoDTO> createShareInfo(@Valid @RequestBody ShareInfoDTO shareInfoDTO) throws URISyntaxException {
        log.debug("REST request to save ShareInfo : {}", shareInfoDTO);
        if (shareInfoDTO.getId() != null) {
            return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert("shareInfo", "idexists", "A new shareInfo cannot already have an ID")).body(null);
        }
        ShareInfo shareInfo = shareInfoMapper.shareInfoDTOToShareInfo(shareInfoDTO);
        shareInfo = shareInfoRepository.save(shareInfo);
        ShareInfoDTO result = shareInfoMapper.shareInfoToShareInfoDTO(shareInfo);
        return ResponseEntity.created(new URI("/api/share-infos/" + result.getId()))
            .headers(HeaderUtil.createEntityCreationAlert("shareInfo", result.getId().toString()))
            .body(result);
    }

    /**
     * PUT  /share-infos : Updates an existing shareInfo.
     *
     * @param shareInfoDTO the shareInfoDTO to update
     * @return the ResponseEntity with status 200 (OK) and with body the updated shareInfoDTO,
     * or with status 400 (Bad Request) if the shareInfoDTO is not valid,
     * or with status 500 (Internal Server Error) if the shareInfoDTO couldnt be updated
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @RequestMapping(value = "/share-infos",
        method = RequestMethod.PUT,
        produces = MediaType.APPLICATION_JSON_VALUE)
    @Timed
    @Secured(AuthoritiesConstants.ADMIN)
    public ResponseEntity<ShareInfoDTO> updateShareInfo(@Valid @RequestBody ShareInfoDTO shareInfoDTO) throws URISyntaxException {
        log.debug("REST request to update ShareInfo : {}", shareInfoDTO);
        if (shareInfoDTO.getId() == null) {
            return createShareInfo(shareInfoDTO);
        }
        ShareInfo shareInfo = shareInfoMapper.shareInfoDTOToShareInfo(shareInfoDTO);
        shareInfo = shareInfoRepository.save(shareInfo);
        ShareInfoDTO result = shareInfoMapper.shareInfoToShareInfoDTO(shareInfo);
        return ResponseEntity.ok()
            .headers(HeaderUtil.createEntityUpdateAlert("shareInfo", shareInfoDTO.getId().toString()))
            .body(result);
    }

    /**
     * GET  /share-infos : get all the shareInfos.
     *
     * @param pageable the pagination information
     * @return the ResponseEntity with status 200 (OK) and the list of shareInfos in body
     * @throws URISyntaxException if there is an error to generate the pagination HTTP headers
     */
    @RequestMapping(value = "/share-infos",
        method = RequestMethod.GET,
        produces = MediaType.APPLICATION_JSON_VALUE)
    @Timed
    @Secured(AuthoritiesConstants.ADMIN)
    public ResponseEntity<List<ShareInfoDTO>> getAllShareInfos(Pageable pageable)
        throws URISyntaxException {
        log.debug("REST request to get a page of ShareInfos");
        Page<ShareInfo> page = shareInfoRepository.findAll(pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/share-infos");
        return new ResponseEntity<>(shareInfoMapper.shareInfosToShareInfoDTOs(page.getContent()), headers, HttpStatus.OK);
    }

    /**
     * GET  /share-infos/:id : get the "id" shareInfo.
     *
     * @param id the id of the shareInfoDTO to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the shareInfoDTO, or with status 404 (Not Found)
     */
    @RequestMapping(value = "/share-infos/{id}",
        method = RequestMethod.GET,
        produces = MediaType.APPLICATION_JSON_VALUE)
    @Timed
    @Secured(AuthoritiesConstants.ADMIN)
    public ResponseEntity<ShareInfoDTO> getShareInfo(@PathVariable Long id) {
        log.debug("REST request to get ShareInfo : {}", id);
        ShareInfo shareInfo = shareInfoRepository.findOne(id);
        ShareInfoDTO shareInfoDTO = shareInfoMapper.shareInfoToShareInfoDTO(shareInfo);
        return Optional.ofNullable(shareInfoDTO)
            .map(result -> new ResponseEntity<>(
                result,
                HttpStatus.OK))
            .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }

    /**
     * DELETE  /share-infos/:id : delete the "id" shareInfo.
     *
     * @param id the id of the shareInfoDTO to delete
     * @return the ResponseEntity with status 200 (OK)
     */
    @RequestMapping(value = "/share-infos/{id}",
        method = RequestMethod.DELETE,
        produces = MediaType.APPLICATION_JSON_VALUE)
    @Timed
    @Secured(AuthoritiesConstants.ADMIN)
    public ResponseEntity<Void> deleteShareInfo(@PathVariable Long id) {
        log.debug("REST request to delete ShareInfo : {}", id);
        shareInfoRepository.delete(id);
        return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert("shareInfo", id.toString())).build();
    }

}
